package admin

import (
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"mall-go/common"
	"mall-go/dto"
	"mall-go/model"
	"mall-go/response"
	"mall-go/util"
	"mall-go/vo"
	"strconv"
)

type RegisterUserController struct {
	DB *gorm.DB
}

//用户的一些数据库操作我刚开始写的时候没有做封装，那这里就直接把数据库操作写在controller里了

// List 返回商城注册用户列表
func (receiver RegisterUserController) List(ctx *gin.Context) {
	//获取分页数据
	pageNumber, _ := strconv.Atoi(ctx.Query("pageNumber"))
	pageSize, _ := strconv.Atoi(ctx.Query("pageSize"))
	if pageNumber < 1 || pageSize < 10 {
		panic("参数异常")
	}

	//查询当前页的user集合
	var users []model.MallUser
	receiver.DB.Order("create_time desc").Offset((pageNumber - 1) * pageSize).Limit(pageSize).Find(&users)
	//查询总数
	var total int
	receiver.DB.Model(&model.MallUser{}).Count(&total)

	//封装vo
	usersResultVO := vo.UserPageResult{
		PageResult: vo.PageResult{
			TotalCount: total,
			PageSize:   pageSize,
			TotalPage:  total / pageSize,
			CurrPage:   pageNumber,
		},
		List: users,
	}
	response.Success(ctx, gin.H{"usersVO": usersResultVO}, "Success")
}

// LockUser 锁定用户
func (receiver RegisterUserController) LockUser(ctx *gin.Context) {
	//获取请求参数
	lockStatus, _ := strconv.Atoi(ctx.Params.ByName("lockStatus"))

	var param dto.BatchIdParam
	if err := ctx.Bind(&param); err != nil {
		panic(err)
	}
	if len(param.UserIds) < 1 {
		response.Failure(ctx, nil, "参数异常")
	}
	if lockStatus != 0 && lockStatus != 1 {
		panic("非法参数")
	}
	// 批量锁定/解锁用户
	if err := receiver.DB.Debug().Model(&model.MallUser{}).
		Where("user_id in ("+util.Convert(param.UserIds)+")").
		Update("locked_flag", lockStatus).Error; err != nil {
		panic(err)
	}
	response.Success(ctx, nil, "修改成功")
}

func NewRegisterUserController() RegisterUserController {
	DB := common.GetDB()
	return RegisterUserController{DB: DB}
}
